Skip to content

Latest commit

 

History

History
92 lines (77 loc) · 2.27 KB

File metadata and controls

92 lines (77 loc) · 2.27 KB

438. Find All Anagrams in a String

Given two strings s and p, return an array of all the start indices ofp's anagrams ins. You may return the answer in any order.

Example 1:

Input: s = "cbaebabacd", p = "abc" Output: [0,6] Explanation: The substring with start index = 0 is "cba", which is an anagram of "abc". The substring with start index = 6 is "bac", which is an anagram of "abc". 

Example 2:

Input: s = "abab", p = "ab" Output: [0,1,2] Explanation: The substring with start index = 0 is "ab", which is an anagram of "ab". The substring with start index = 1 is "ba", which is an anagram of "ab". The substring with start index = 2 is "ab", which is an anagram of "ab". 

Constraints:

  • 1 <= s.length, p.length <= 3 * 104
  • s and p consist of lowercase English letters.

Solutions (Ruby)

1. Sliding Window

# @param {String} s# @param {String} p# @return {Integer[]}deffind_anagrams(s,p)return[]ifs.size < p.sizecount_p=[0] * 26count_s=[0] * 26ret=[](0...p.size).eachdo |i| count_p[p[i].ord - 97] += 1count_s[s[i].ord - 97] += 1end(0..s.size - p.size).eachdo |i| ret.push(i)ifcount_p == count_sifi + p.size < s.sizecount_s[s[i].ord - 97] -= 1count_s[s[i + p.size].ord - 97] += 1endendretend

Solutions (Rust)

1. Sliding Window

implSolution{pubfnfind_anagrams(s:String,p:String) -> Vec<i32>{if s.len() < p.len(){returnvec![];}let s = s.as_bytes();let p = p.as_bytes();letmut count_p = [0;26];letmut count_s = [0;26];letmut ret = vec![];for i in0..p.len(){ count_p[(p[i] - b'a')asusize] += 1; count_s[(s[i] - b'a')asusize] += 1;}for i in0..=s.len() - p.len(){if count_p == count_s { ret.push(i asi32);}if i + p.len() < s.len(){ count_s[(s[i] - b'a')asusize] -= 1; count_s[(s[i + p.len()] - b'a')asusize] += 1;}} ret }}
close